package com.zwps.common.core.tool;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.MutablePropertySources;

/**
 * 打印当前已经加载的配置内容
 * 
 * @ClassName: PrintEnvironmentTool
 * @Description:
 * @author lyh
 * @date 2023年9月3日 上午1:25:00
 *
 */
public class PrintEnvironmentTool {

    public static void print() {
        ConfigurableEnvironment springEnv = AutowiredBeanTool.getBean(ConfigurableEnvironment.class);
        MutablePropertySources propSrcs = springEnv.getPropertySources();
        // 获取所有配置
        Map<String, String> props = StreamSupport.stream(propSrcs.spliterator(), false)
                .filter(ps -> ps instanceof EnumerablePropertySource)
                .map(ps -> ((EnumerablePropertySource<?>) ps).getPropertyNames()).flatMap(Arrays::stream).distinct()
                .collect(Collectors.toMap(Function.identity(), springEnv::getProperty));

        // key 和 value 之间的最小间隙
        int interval = 20;
        int max = props.keySet().stream().max(Comparator.comparingInt(String::length)).orElse("").length();

        // 打印
        props.keySet().stream().sorted().forEach(k -> {
            int i = max - k.length() + interval;
            String join = String.join("", Collections.nCopies(i, " "));
            System.out.println(String.format("%s%s%s", k, join, props.get(k)));
        });
    }

}
